using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SyncUdp
{
    using DG.Tweening;
    using SyncUdp.Enum;
    using SyncUdp.Event;
    using SyncUdp.Event.GameEvent;
    using SyncUdp.Interface;
    using SyncUdp.MethodExtension;
    using SyncUdp.UI;
    using UnityEngine.UI;

    public interface IUIManager : ISingleton
    {
        public void ShowUI(UIType type);
    }

    /// <summary>
    /// UI 管理器
    /// </summary>
    public class UIManager : AbstractSingleton, IUIManager
    {
        IEventCenter _eventCenter;
        IGameManager _gm;
        List<IUIController> _uis;

        #region 方法实现
        protected override void OnInit()
        {
            _eventCenter = this.GetInstance<IEventCenter>();
            _gm = this.GetInstance<IGameManager>();
            // 之所以不通过 IOC 容器获取，是因为 UI 的单例会在 Start 时加入容器中；
            // 若此时通过容器获取则是获取不到的。
            _uis = new List<IUIController>()
            {
                null,
                _gm.Architecture.transform.Find("UIRoot/Canvas/MainMenuUI").GetComponent<MainMenuUIController>(),
                _gm.Architecture.transform.Find("UIRoot/Canvas/PlayingUI").GetComponent<PlayingUIController>(),
            };
            RegisterEvent<GameCreatedSuccessfullyEvent>(OnGameHasCreated);
            RegisterEvent<GameJoinedSuccessfullyEvent>(OnGameJoinedSuccessfully);
        }

        public void ShowUI(UIType type)
        {
            int index = (int)type;
            if (index <= 0 || index >= _uis.Count)
            {
                if (_gm.IsEditorMode)
                    Debug.LogError($"更换 UI 错误：不存在或无效的 UI 类型：{type}");
                return;
            }
            for (int i = 1; i < _uis.Count; i++)
                if (i == index)
                    _uis[i].Show();
                else
                    _uis[i].Hide();
        }
        #endregion

        #region 回调方法
        void OnGameHasCreated(GameCreatedSuccessfullyEvent e)
        {
            // 显示游戏进行时的 UI 
            ShowUI(UIType.Playing);
        }

        void OnGameJoinedSuccessfully(GameJoinedSuccessfullyEvent e)
        {
            // 显示游戏进行时的 UI 
            ShowUI(UIType.Playing);
        }
        #endregion
    }
}
